package cn.zb.service.impl;

import cn.zb.entity.SysMenu;
import cn.zb.mapper.SysMenuMapper;
import cn.zb.service.SysMenuService;
import cn.zb.vo.MenuVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lewin
* @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
* @createDate 2024-11-22 14:41:18
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Resource
    SysMenuMapper menuMapper;

    @Override
    public List<MenuVO> initMenu(List<Integer> ids) {
        // 查询出所有的菜单和组件
        QueryWrapper<SysMenu> qw = new QueryWrapper<>();
        qw.in(!ids.isEmpty(),"menu_id",ids);
        qw.and(tj->{
            tj.eq("menu_type","M").or().eq("menu_type","C");
        });
        List<SysMenu> sysMenus = menuMapper.selectList(qw);
        // 提取出所有的一级目录
        List<SysMenu> parent = sysMenus.stream()
                .filter(m -> m.getParentId() == 0)
                .sorted(Comparator.comparingLong(SysMenu::getOrderNum))
                .collect(Collectors.toList());
        // 返回所有目录
        return getMenuVo(parent,sysMenus);
    }

    public List<MenuVO> getMenuVo(List<SysMenu> parentMenus, List<SysMenu> allMenus) {
        List<MenuVO> menuVOList = new ArrayList<>();

        for (SysMenu parentMenu : parentMenus) {
            MenuVO menuVO = new MenuVO();
            menuVO.setTitle(parentMenu.getMenuName());
            menuVO.setUrl(parentMenu.getPath());
            menuVO.setIcon(parentMenu.getIcon());
            menuVO.setComponent(parentMenu.getComponent());
            // 递归获取子菜单
            List<SysMenu> childMenus = allMenus.stream()
                    .filter(m -> m.getParentId().equals(parentMenu.getMenuId()))
                    .sorted(Comparator.comparingLong(SysMenu::getOrderNum))
                    .collect(Collectors.toList());
            if (!childMenus.isEmpty()) {
                List<MenuVO> children = getMenuVo(childMenus, allMenus);
                menuVO.setChildren(children);
            }

            menuVOList.add(menuVO);
        }

        return menuVOList;
    }
}




